import time
from datetime import datetime

from sqlmodel import Session, select, func
from typing import Optional, List

from app.exception.base import AppException, HttpResp
from app.models.system_menu import SystemMenu, SystemMenuEditIn, SystemMenuCreateIn
from app.utils.array import ArrayUtil


class SystemMenuService:
    def __init__(self, session: Session):
        self.session = session


    async def all_list(self) -> List:
        statement = select(SystemMenu)
        all_menu = self.session.exec(statement).all()

        # 将 ORM 对象转换为字典形式，并排除空值字段
        menu_list = [menu.dict(exclude_none=True) for menu in all_menu]
        return menu_list

    async def tree_list(self) -> List:
        statement = select(SystemMenu).order_by(SystemMenu.sort.desc(), SystemMenu.id.desc())
        all_menu = self.session.exec(statement).all()

        # 将 ORM 对象转换为字典形式，并排除空值字段
        menu_list = [menu.dict(exclude_none=True) for menu in all_menu]
        return ArrayUtil.list_to_tree( menu_list,'id', 'pid', 'children')

    async def detail(self, id_: int):
        menu = self.session.get(SystemMenu, id_)
        return menu

    async def add(self, create_in: SystemMenuCreateIn):
        """新增菜单"""
        create_dict = create_in.dict()
        # create_dict['create_time'] = datetime.now()
        # create_dict['update_time'] = datetime.now()
        menu_item = SystemMenu(**create_dict)
        self.session.add(menu_item)
        self.session.commit()
        self.session.refresh(menu_item)
        return menu_item

    async def edit(self, edit_in: SystemMenuEditIn,):
        menu_item = self.session.get(SystemMenu, edit_in.id)
        if not menu_item:
            raise AppException(HttpResp.FAILED, msg='菜单已不存在!')

        # 更新菜单项的字段
        for key, value in edit_in.dict().items():
            if hasattr(menu_item, key):
                setattr(menu_item, key, value)

        # 更新 update_time 字段
        # menu_item.update_time = datetime.now()
        # 提交更改到数据库
        self.session.commit()
        self.session.refresh(menu_item)
        return menu_item


    async def delete(self, id_: int):
        menu = self.session.get(SystemMenu, id_)
        if not menu:
            raise AppException(HttpResp.FAILED, msg='菜单已不存在!')
        # 检查是否有子菜单项
        sub_menu_count_statement = (
            select(func.count())
            .select_from(SystemMenu)
            .where(SystemMenu.pid == id_)
        )
        sub_menu_count = self.session.exec(sub_menu_count_statement).one()
        print('sub_menu_count',  sub_menu_count)
        if sub_menu_count > 0:
            raise AppException(HttpResp.FAILED, msg='该菜单有子菜单项，无法删除!')
        # 删除菜单项
        self.session.delete(menu)
        self.session.commit()
        return "菜单删除成功"
